import csv
import json


class csv2():
    def __init__(self, file):
        self.csv_file = file
        self.csv_data = {}
        self.load(file)
        pass

    def load(self, file):
        try:
            with open(file, 'r') as csv_file:
                csv_dict = csv.DictReader(csv_file, restkey=None, restval=None)
                for obj in csv_dict:
                    self.csv_data[obj['id']] = obj
        except:
            pass

        return True

    def merge(self, file):
        with open(file, 'r') as csv_file:
            csv_dict = csv.DictReader(csv_file, restkey=None, restval=None)
            for obj in csv_dict:
                if not obj['id'] in self.csv_data.keys():
                    self.csv_data[obj['id']] = {}
                for key in obj:
                    self.csv_data[obj['id']][key] = obj[key]

    def save_as(self, file):
        out = []
        keys = []

        for objKey in self.csv_data:
            obj = self.csv_data[objKey]
            out.append(obj)
            for key in obj:
                if not (key in keys):
                    keys.append(key)

        with open(file, 'w') as csv_file:
            csv.register_dialect('ns', lineterminator='\n')
            writer = csv.DictWriter(csv_file, fieldnames=keys, dialect='ns')

            writer.writeheader()
            writer.writerows(out)
            return True

        return False

    def get_data(self):
        return self.csv_data

    def filter_row_by_key_value(self, key, value):
        out = []
        if self.csv_data:
            csv_dict = self.csv_data
            for objKey in csv_dict:
                obj = csv_dict[objKey]
                if obj[key] == value:
                    out.append(obj)
        return json.dumps(out)

    def filter_col_by_key(self, key):
        out = []
        if self.csv_data:
            csv_dict = self.csv_data
            for objKey in csv_dict:
                obj = csv_dict[objKey]
                try:
                    if obj[key] != "":
                        out.append({key: obj[key]})
                except:
                    pass
        return json.dumps(out)

    def update_row_by_data(self, json_data):
        if 'rows' in json_data.keys():
            json_data = json_data['rows']

        max_id = 0

        if self.csv_data:
            return False

        for objKey in self.csv_data:
            obj = self.csv_data[objKey]
            try:
                id = int(obj['id'])
                if max_id < id:
                    max_id = id
            except:
                pass

        for uobj in json_data:
            if uobj['id'] in self.csv_data.keys():
                for k in uobj:
                    self.csv_data[uobj['id']][k] = uobj[k]
            elif uobj['id'] != '':
                self.csv_data[uobj['id']] = {}
                for k in uobj:
                    self.csv_data[uobj['id']][k] = uobj[k]
            else:
                max_id = max_id + 1
                self.csv_data[str(max_id)] = {}
                for k in uobj:
                    self.csv_data[str(max_id)][k] = uobj[k]
                self.csv_data[str(max_id)]['id'] = str(max_id)

        self.save_as(self.csv_file)
        return True

    def update_row_by_json(self, jsonFile):
        if not self.csv_data:
            return False

        with open(jsonFile, 'r') as fp:
            update_dict = json.load(fp)
            update_row_by_data(update_dict)

if __name__ == "__main__":
    obj = csv2('status.csv')

    obj.filter_col_by_key('status')

    obj.filter_row_by_key_value('status', 'Good')
    # obj.update_row_by_json('update.json')
    obj.merge('status_m.csv')
    obj.save_as('status_out.csv')



